package z.explorer.ui.common;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashMap;

import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;

public abstract class ZTabbedPane extends JTabbedPane {

	protected ArrayList<String> components = new ArrayList<String>();

	public int indexOf(String key) {
		return components.indexOf(key);
	}

	public abstract String getName();

	public JPanel initTab(String key) {
		JPanel titlePane = new JPanel();
		titlePane.setOpaque(false);
		titlePane.setLayout(new FlowLayout(FlowLayout.LEFT));
		JPanel closePane = new JPanel();
		closePane.setOpaque(false);
		closePane.setLayout(new FlowLayout(FlowLayout.RIGHT));
		JLabel titleLabel = new JLabel(getName() + " - " + key);
		titleLabel.setBorder(BorderFactory.createEmptyBorder());
		titlePane.add(titleLabel);
		JButton closeButton = new JButton("X");
		closeButton.setBorder(BorderFactory.createEtchedBorder());
		closeButton.setOpaque(true);
		closeButton.addActionListener(new CloseActionListener(key));
		closePane.add(closeButton);
		JPanel pane = new JPanel();
		pane.setLayout(new BorderLayout());
		pane.add(titlePane, BorderLayout.CENTER);
		pane.add(closePane, BorderLayout.EAST);
		pane.setOpaque(false);
		return pane;
	}

	public void addPanel(String key, JPanel p) {
		int index = indexOf(key);
		if (index == -1) {
			// int count = getComponentCount();
			components.add(key);
			index = indexOf(key);

		} else {
			remove(index);
		}
		add(p, index);
		JPanel pane = initTab(key);
		setTabComponentAt(index, pane);
		setSelectedIndex(index);
	}

	public void removePanel(String key) {
		int index = indexOf(key);
		if (index == -1)
			return;
		else {
			components.remove(index);
			remove(index);
		}
	}

	public class CloseActionListener implements ActionListener {

		private String key;

		public CloseActionListener(String key) {
			this.key = key;
		}

		@Override
		public void actionPerformed(ActionEvent e) {
			// TODO Auto-generated method stub
			removePanel(key);
		}

	}
}
